/**
 * 无纸化维保审批
 */
import { Component, OnInit } from "@angular/core";
import {NzNotificationService, NzModalService, NzModalSubject,} from "ng-zorro-antd";
import {
  FormBuilder,
} from "@angular/forms";
import { HttpServcie } from "../../../service/http.service";
import { Router } from "@angular/router";
import {Config} from "../../../service/config";
import * as moment from "moment";
import {PaperlessMaintApplyBean} from "../bean/paperlessMaint-apply.bean";

@Component({
  selector: "paperlessMaint-approval",
  templateUrl: "./paperlessMaint-approval.html",
  styleUrls: ["./paperlessMaint-approval.scss"]
})
export class PaperlessMaintApproval implements OnInit {

  constructor(
    private _notification: NzNotificationService,
    private fb: FormBuilder,
    private httpServcie: HttpServcie,
    private router: Router,
    private modalService: NzModalService
  ) {
    this.user = JSON.parse(window.localStorage.getItem("user"));
  }
  user : any;
  partyLevel : string;
  partyType : string;
  applyTypes = Config.APPLY_TYPES;  //按需维保申请状态
  paperlessBean : PaperlessMaintApplyBean = new PaperlessMaintApplyBean();
  isShowButton : any = true;
  showFlag: boolean;
  //查询参数
  applyStatus = Config.PAPERLESS_APPLY_STATUS;  //按需维保申请状态
  partyName : string;
  contacts : string;
  //返回的集合
  dataList : any = [];
  //多选框参数
  allChecked: any = false;
  indeterminate: any = false;
  updateData: any = {};
  total = 0;

  //模态框参数
  modelTitle : string = "";
  modal: any = 0;
  currentModal: NzModalSubject;

  tempPaperlessBean : PaperlessMaintApplyBean = new PaperlessMaintApplyBean();
  //其他参数
  config = Config;
  ngOnInit(): void {
    this.user = JSON.parse(window.localStorage.getItem("user"));
    this.partyLevel = this.user.partyLevel;
    this.partyType = this.user.partyType;
    this.paperlessBean.currentPage = 1;
    this.paperlessBean.pageSize = 10;
    this.query();
    console.log(this.partyLevel + "," + this.partyType);
  }

  query(){
    if(this.paperlessBean.startDate){
      this.paperlessBean.startDate = moment(this.paperlessBean.startDate).format("YYYY-MM-DD");
    }
    if(this.paperlessBean.endDate){
      this.paperlessBean.endDate = moment(this.paperlessBean.endDate).format("YYYY-MM-DD");
    }
    if(this.partyLevel == '2'){ //当前监管单位是区级单位
      this.paperlessBean.jgPartyId = this.user.partyId;
    }
    if(this.partyLevel == '1'){ //当前监管单位是市级单位
      this.paperlessBean.parentParentPartyId = this.user.partyId;
    }

    this.httpServcie.queryPaperlessMaintance(this.paperlessBean).subscribe(data=>{
      if(data.status == 200){
        this.dataList = data.data.list;
      }else{
        this._notification.create("error", "错误提示", "查询失败");
      }
    })

  }


  /**
   * 查看电梯详情
   */
  detail(data){
    this.router.navigate(["/home/paperlessMaintElevator",{"elevatorIds" : data.elevatorIds, "jgPartyId" : data.jgPartyId}]);
  }

  /**
   *中止维保试点
   */
  suspend(titleSuspend, contentSuspend, footerSuspend) {
    let tempList : any = [];
    this.dataList.forEach(data => {
      if (!data.disabled && data.checked) {
        tempList.push(data);
        this.tempPaperlessBean = data;
      }
    });

    if (tempList.length == 0) {
      // 异常
      this._notification.create("error", "错误提示", "请选中一条数据！");
      return;
    }
    if (tempList.length > 1) {
      // 异常
      this._notification.create("error", "错误提示", "只能选中一条数据！");
      return;
    }
    if(this.tempPaperlessBean.applyStatus != '2'){
      this._notification.create("error", "错误提示", "选中的记录,未被审批或已中止！");
      return;
    }

    this.currentModal = this.modalService.open({
      title: "中止申请",
      content: contentSuspend,
      width: 800,
      footer: false,
      style: {
        top: "20px"
      }
    });
  }

  /**
   * 对无纸化维保申请进行审批
   * @param titleAr
   * @param contentAr
   * @param footerAr
   * @param data
   */
  approve1(titleAr,contentAr,footerAr,data){
    this.tempPaperlessBean = data;
    this.currentModal = this.modalService.open({
      title: "审批无纸化申请",
      content: contentAr,
      width: 1000,
      footer: false,
      style: {
        top: "20px"
      }
    });
    if(data.applyStatus == '1'){
      this.showFlag = false;
     }else{
      this.showFlag = true;
    }
  }

  /**
   * 市级监管部门对区级监管提交的中止申请审批
   */
  approve(titleApprove,contentApprove,footerApprove,data){
    this.tempPaperlessBean = data;
    this.currentModal = this.modalService.open({
      title: "审批无纸化中止申请",
      content: contentApprove,
      width: 1000,
      footer: false,
      style: {
        top: "20px"
      }
    });
    if(data.applyStatus == '4'){
      this.showFlag = false;
    }else{
      this.showFlag = true;
    }
  }

  applySubmit(){
    if(this.tempPaperlessBean.remarks == null || typeof (this.tempPaperlessBean.remarks) == 'undefined'){
      this._notification.create("warning", "警告提示", "请填写审批备注");
      return;
    }
    this.httpServcie.updatePaperlessMaintance(this.tempPaperlessBean).subscribe(data =>{
      if(data.status == 200){
        this._notification.create("success", "提示", "提交成功");
      }else{
        this._notification.create("error", "错误提示", "提交失败");
      }
      this.currentModal.destroy();
    });

  }

  /**
   * 中止申请
   */
  submit(){
    if(this.tempPaperlessBean.suspendReason == null || typeof (this.tempPaperlessBean.suspendReason) == 'undefined'){
      this._notification.create("warning", "警告提示", "请填写申请原因");
      return;
    }
    this.tempPaperlessBean.applyStatus = '4'; //中止申请中
    this.httpServcie.updatePaperlessMaintance(this.tempPaperlessBean).subscribe(data =>{
      if(data.status == 200){
        this._notification.create("success", "提示", "提交成功");
      }else{
        this._notification.create("error", "错误提示", "提交失败");
      }
      this.currentModal.destroy();
    });
  }

  /**
   * 中止申请审批
   */
  suspendSubmit(){
    if(this.tempPaperlessBean.suspendRemarks == null || typeof (this.tempPaperlessBean.suspendRemarks) == 'undefined'){
      this._notification.create("warning", "警告提示", "请填写审批备注");
      return;
    }
    this.httpServcie.updatePaperlessMaintance(this.tempPaperlessBean).subscribe(data =>{
      if(data.status == 200){
        this._notification.create("success", "提示", "提交成功");
      }else{
        this._notification.create("error", "错误提示", "提交失败");
      }
      this.currentModal.destroy();
    });

  }


  /**
   * 下载承诺书文件
   * @param data
   * @param flag
   */
  downloadFile(data,flag){
    if(flag == 1){
      if (!data.letterOfCommitmentDoc) {
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = data.letterOfCommitmentDoc.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '承诺书' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }
    }
  }

  download(url, name) {
    let link = document.createElement('a');
    let body = document.querySelector('body');

    this.getBlob(this.config.IP + this.config.API.getUpload + url).then(blob => {
      link.href = window.URL.createObjectURL(blob);
      link.download = name;
      // fix Firefox
      link.style.display = 'none';
      body.appendChild(link);
      link.click();
      body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    });
  }

  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }
  quit() {
    this.currentModal.destroy();
    this.query();
  }

  //添加后返回的结果
  addOutPut($event) {
    setTimeout(() => {
      this.currentModal.destroy();
      this.currentModal = null;
    }, 500);
  }

  displayDataChange($event){
    this.dataList = $event;
    this.refreshStatus();
  }

  checkAll(value){
    if (value) {
      this.dataList.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.dataList.forEach(data => data.checked = false);
    }
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.dataList.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.dataList.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }

  //分页处理
  nzPageSizeChange(event){
    this.paperlessBean.pageSize = event;
    this.paperlessBean.currentPage = 1;
    this.query();
  }

  nzPageIndexChange(event){
    this.paperlessBean.currentPage = event;
    this.query();
  }

  nzPageIndexClickChange(event){
    this.paperlessBean.currentPage = event;
    this.query();
  }


  //添加返回
  addCall(event) {
    this.currentModal.destroy();
    this.query();
  }
  // 查询面板
  panels = {
    active: true,
    name: "查询",
    disabled: false,
    childPanel: [
      {
        active: false,
        name: "查询"
      }
    ]
  };
}
